package com.dyp.global_exception_handler.ctr;

import com.dyp.global_exception_handler.model.User;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping("/user")
public class UserController {

    // 使用 @InitBinder 注解注册自定义数据绑定,
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        // 1. 去除字符串两边的空白字符 对PathVariable RequestParam ModelAttribute有效
        binder.registerCustomEditor(String.class,  new StringTrimmerEditor(true));
        // 2 3. 在 v3和v2里是有区别的！
        // 2. 自定义 name 字段的转换（示例：自动大写首字母）对PathVariable RequestParam ModelAttribute有效且在对象里的属性是name字段有效
        binder.registerCustomEditor(String.class,  "name", new NameEditor());

        // 3. 自定义 address 字段的转换（示例：去掉特殊字符）对PathVariable RequestParam ModelAttribute有效且在对象里的属性是address字段有效
        binder.registerCustomEditor(String.class, "address",new AddressEditor());
    }

    @PostMapping("/create")
    @ResponseBody
    public String createUser(@ModelAttribute User user) {
        return "Processed User: " + user.toString();
    }

    @GetMapping("/get/{name}/info")
    @ResponseBody
    public String getUserInfo(@PathVariable String name,
                              @RequestParam String address) {
        return "Processed User: " + name + "  " + address;
    }

    @PostMapping("/create/by/requestbody")
    @ResponseBody
    public String createUserbyrequest(@RequestBody User user) {
        return "Processed User: " + user.toString();
    }
}